package com.wego.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wego.bean.PageBean;
import com.wego.domain.entity.PopularText;
import com.wego.domain.query.PopularTextQuery;
import com.wego.mapper.PopularTextMapper;
import com.wego.service.PopularTextService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PopularTextServiceImpl implements PopularTextService {
@Autowired
private PopularTextMapper popularTextMapper;

@Override
public PageBean<PopularText> getPage(PopularTextQuery popularTextQuery) {
    final Integer pageNum = popularTextQuery.getPageNum();
    final Integer pageSize = popularTextQuery.getPageSize();
    final Page<PopularText> page = PageHelper.startPage(pageNum, pageSize);
        popularTextMapper.selectWithCondition(popularTextQuery);
        return PageBean.page2pageBean(page);
    }

    @Override
    public PopularText getById(Integer id) {
        return popularTextMapper.selectByPrimaryKey(id);
    }

    @Override
    public int insert(PopularText popularText) {
        if (popularText == null) {
            throw new IllegalArgumentException("PopularText cannot be null");
        }
        if (popularText.getTitle() == null) {
            throw new IllegalArgumentException("Title cannot be null");
        }
        //设置更新时间为当前时间
        popularText.setCreateTime(LocalDateTime.now());
        popularText.setUpdateTime(LocalDateTime.now());
        return popularTextMapper.insertSelective(popularText);
    }

    @Override
    public int deleteById(Integer id) {
        return popularTextMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(String ids) {
        final String[] split = ids.split(",");
        return popularTextMapper.deleteByPrimaryKeyIn(split);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public int batchInsert(List<PopularText> popularTextList) {
        return popularTextMapper.batchInsert(popularTextList);
    }

    @Override
    public int update(PopularText popularText) {
        if (popularText == null) {
            throw new IllegalArgumentException("PopularText cannot be null");
        }
        if (popularText.getId() == null) {
            throw new IllegalArgumentException("ID cannot be null");
        }
    return popularTextMapper.updateByPrimaryKeySelective(popularText);
    }
}
